package org.ade.monak.anak.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ade.monak.anak.Variable.TipePesanMonak;
import org.ade.monak.anak.entity.IPesanData;
import org.ade.monak.anak.entity.Ortu;
import org.ade.monak.anak.map.service.Tracker;
import org.ade.monak.anak.service.gate.InternetPushMonakAnak;
import org.ade.monak.anak.service.gate.MultiSMSReceiver;
import org.ade.monak.anak.service.gate.monak.ReceiverPendaftaranAnak;
import org.ade.monak.anak.service.gate.monak.ReceiverPesanData;
import org.ade.monak.anak.service.gate.monak.ReceiverRequestLogMonak;
import org.ade.monak.anak.service.gate.monak.ReceiverStartMonitoring;
import org.ade.monak.anak.service.gate.monak.ReceiverStopMonitoring;
import org.ade.monak.anak.service.gate.monak.ReceiverTrackingMode;
import org.ade.monak.anak.service.gate.monak.SenderKonfirmasi;
import org.ade.monak.anak.service.gate.monak.SenderLokasi;
import org.ade.monak.anak.service.storage.DatabaseManagerAnak;
import org.ade.monak.anak.service.storage.LogMonakFileManager;
import org.ade.monak.anak.service.storage.PreferenceMonitoringManager;
import org.ade.monak.anak.util.MonakJsonConverter;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsMessage;
import android.util.Log;

public class MonakServiceAnak extends Service{

    
	@Override
	public void onCreate() {
        Log.d("background service", "creating service");
		pref = new PreferenceMonitoringManager(this);
		pref.setActiveService();
		
		internetPush = new InternetPushMonakAnak(this);
		internetPush.startConnection();
		
		databaseManager = new DatabaseManagerAnak(this);	
		
		databaseThread	= new DatabaseThreadService();
	}

	
	@Override
	public void onDestroy() {
		List<Ortu> ortus = databaseManager.getAllOrtu(false);
		if(ortus!=null){
			for(Ortu ortu:ortus){
				SenderKonfirmasi sender = new SenderKonfirmasi(this, ortu);
				sender.sendKonfirmasiDeAktifAnak(ortu);
			}
		}
		
		if(internetPush!=null){
			internetPush.stopConnection();
			internetPush = null;
		}
		
		if(tracker!=null){
			tracker.stopTracking();
			tracker = null;	
		}
		
		if(mainMonitoring!=null){
			mainMonitoring.stopMonitoring();
			mainMonitoring = null;
		}
		
		pref.setInActiveService();
		super.onDestroy();
	}
	
	public DatabaseThreadService getDatabaseThread(){
		return databaseThread;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("background service", "service started");
        
        if(mainMonitoring==null){
    		mainMonitoring = new MainMonitoring(this, databaseThread);	
    	}
        
        if(!mainMonitoring.isStart()){
        	mainMonitoring.startMonitoring();
        }
        
        if(tracker==null){
        	tracker = new Tracker(this, mainMonitoring);
        }
                
        if(!tracker.isStartMonitoring()){
        	tracker.startTracking();
        }
        
        
        
        if(intent!=null){
        	Bundle bundle = intent.getExtras();
            if(bundle!=null){
            	switch(bundle.getInt(START_CALL)){
	    	        case RECEIVER_SMS:{
	    	        	Log.d("background service", "masuk receiver SMS");
	    	        	receiveSMS(bundle);
	    	        	break;
	    	        }case RECEIVER_INTERNET:{
	    	        	routeToGateMonak(bundle.getString(PESAN_INTERNET));
	    	        	break;
	    	        }
            	}	
            	

                if(bundle.getInt(STATUS_INTERNET)==START){
            		if(!internetPush.isStart()){
                		internetPush.startConnection();            			
            		}

            	}
            }
        	
        }
        
                
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		if(binderService==null){
			binderService = new BinderService(this);
		}
		return binderService;
	}
	
	
	private void receiveSMS(Bundle bundle){
		SmsMessage[] msgs = null;

        String str = "";            
        if (bundle != null)
        {
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            String noHP="";
            byte[] data = null;
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); 
                noHP=msgs[i].getOriginatingAddress();
                data= msgs[i].getUserData();
                
                for(int index=0; index<data.length; ++index)
                {
                        str += Character.toString((char)data[index]);
                }
            }
            
            String [] multiSplit = str.split("#");
            if(multiSplit.length>3){
            	
            	MultiSMSReceiver multiSms = mapMultiSms.get(multiSplit[0]);
            	
            	if(multiSms==null){
            		multiSms = new MultiSMSReceiver();
            		mapMultiSms.put(multiSplit[0], multiSms);
            	}
            	multiSms.addPesan(str);
            	if(multiSms.isDone()){
            		str = multiSms.getPesan();
            		mapMultiSms.remove(multiSplit[0]);
            	}else{
                    LogMonakFileManager.debug("isi sms0 : "+str);
            		return;
            	}
            }
            
//            if(str.contains("#")){
//            	pendingPesan += str.replace("#","");
//
//                LogMonakFileManager.debug("isi pending pesan : "+pendingPesan);
//            	return;
//            }else{
//            	pendingPesan +=str;
//            	str = pendingPesan;
//            	pendingPesan="";
//            }

            LogMonakFileManager.debug("dapet pesan sms : "+str);
            
            //.... spesial filter pesan data Monitoring....
            String[]stringSplit = str.split(",");
            if(stringSplit[0].equals(""+TipePesanMonak.PENDAFTARAN_ANAK)||
            		stringSplit[0].equals(""+TipePesanMonak.ANAK_UPDATE)||
            		stringSplit[0].equals(""+TipePesanMonak.ANAK_DELETE)){
            	str = str+","+noHP;
            }
            //.........................................
            
            routeToGateMonak(str);
        }
	}
	
	private void routeToGateMonak(String str){
		String[] cvs = str.split(",");
		int status = 0;
		Log.d("MonakService", str);
		
        try{
        	status = Integer.parseInt(cvs[0]);
        }catch(NumberFormatException ex){
        	Log.d("MonakService", "gagal"+str);
			
        }
        
		switch(status){
			case TipePesanMonak.DATAMONITORING_BARU:{
			}case TipePesanMonak.DATAMONITORING_DELETE:{	
			}case TipePesanMonak.DATAMONITORING_UPDATE:{
				String idOrtu = str.substring(str.lastIndexOf(",")+1);
				Ortu ortu = databaseManager.getOrtuByIdOrtu(idOrtu, false);
				LogMonakFileManager.debug("isi id ortu adalah : "+idOrtu);
				str = str.substring(str.indexOf(",")+1);
	        	
				IPesanData pesanData = MonakJsonConverter.convertJsonToPesanData(str);
				
	        	if(pesanData!=null){
	        		ReceiverPesanData receiverPesanData = new ReceiverPesanData();
	        		receiverPesanData.menerimaPesanData(this, databaseThread, pesanData, ortu);	
	        	}
				break;
			}case TipePesanMonak.REQUEST_LOCATION_ANAK:{
	    		Ortu ortu = databaseManager.getOrtuByIdOrtu(cvs[2], false);
	    		SenderLokasi sender = new SenderLokasi(this,ortu);
	    		sender.sendLocationSingleRequest(cvs[1]);
	        	break;
	    	}case TipePesanMonak.REQUEST_LOG_LOCATION:{
	    		Ortu ortu = databaseManager.getOrtuByIdOrtu(cvs[1], false);
	    		ReceiverRequestLogMonak receiver = new ReceiverRequestLogMonak(this, databaseThread, ortu);
	    		receiver.receiveRequestLogLocation();
	    		break;
	    	}case TipePesanMonak.REQUEST_START_TRACKING:{
	    		Ortu ortu = databaseManager.getOrtuByIdOrtu(cvs[1], false);
	    		ReceiverTrackingMode tracking = new ReceiverTrackingMode(this, databaseThread, ortu);
	    		tracking.startTrackingMode();
	    		break;
	    	}case TipePesanMonak.REQUEST_STOP_TRACKING:{
	    		Ortu ortu = databaseManager.getOrtuByIdOrtu(cvs[1], false);
	    		ReceiverTrackingMode tracking = new ReceiverTrackingMode(this,databaseThread, ortu);
	    		tracking.stopTrackingMode();
	    		break;
	    	}case TipePesanMonak.START_MONITORING:{
	    		Ortu ortu = databaseManager.getOrtuByIdOrtu(cvs[2], false);
	    		ReceiverStartMonitoring onMonitoring = new ReceiverStartMonitoring(this,databaseThread, ortu);
	    		onMonitoring.startMonitoring(cvs[1]);
	    		break;
	    	}case TipePesanMonak.PENDAFTARAN_ANAK:{
	    		//tidak mengambil ortu dulu,, karena... disinilah ortu didaftarkan pertama kali....
	    		ReceiverPendaftaranAnak receiver = new ReceiverPendaftaranAnak(this, databaseThread, cvs[2]);
	    		receiver.receivePendaftaranAnak(cvs[3], cvs[1]);
	    		break;
	    	}case TipePesanMonak.ANAK_UPDATE:{
	    		//tidak mengambil ortu dulu,, karena... disinilah ortu didaftarkan pertama kali....
	    		ReceiverPendaftaranAnak receiver = new ReceiverPendaftaranAnak(this, databaseThread, cvs[2]);
	    		receiver.receiveUpdateAnak(cvs[3],cvs[1]);
	    		break;
	    	}case TipePesanMonak.ANAK_DELETE:{
	    		
	    		ReceiverPendaftaranAnak receiver = new ReceiverPendaftaranAnak(this, databaseThread, cvs[2]);
	    		receiver.receiveHapusAnak(cvs[3],cvs[1]);
	    		break;
	    	}case TipePesanMonak.STOP_MONITORING:{
	    		Ortu ortu = databaseManager.getOrtuByIdOrtu(cvs[2], false);
	    		ReceiverStopMonitoring receiver = new ReceiverStopMonitoring(this, databaseThread, ortu);
	    		receiver.stopService(cvs[1]);
	    		break;
	    	}
	    }
	}
	
	private DatabaseThreadService databaseThread;
	
	private Map<String, MultiSMSReceiver> mapMultiSms = new HashMap<String, MultiSMSReceiver>();
	
	private PreferenceMonitoringManager 	pref;
	
	private DatabaseManagerAnak databaseManager;
		
	private InternetPushMonakAnak internetPush;
	
	private BinderService binderService;
	private Tracker tracker;
	private MainMonitoring mainMonitoring;
	

	public final static String STATUS_INTERNET					= "status_internet";
	public final static String PESAN_INTERNET			= "pesan_internet";
	public final static String START_CALL				= "start_call";
	public final static String MONAK_SERVICE_ANAK		= "monak_service_anak";
	public final static String WAITING_LOCATION 		= "waiting_location";
	public final static String WAITING_LOG_LOCATION		= "waiting_log_location";
	public final static String WAITING_KONFIRMASI_AKTIF	= "waiting_konfirmasi_aktif";
	public final static String STORAGE_WAITING_LOCATION = "storage_waiting_location";
	
	public final static int RECEIVER_SMS 				= 1;
	public final static int RECEIVER_INTERNET			= 2;
	
	public final static int START	= 1;
	public final static int STOP	= 2;
	
	public class BinderService extends Binder{
		public BinderService(MonakServiceAnak monakService){
			this.monakService = monakService;
		}
		
		public MonakServiceAnak getMonakService(){
			if(monakService!=null){
				return monakService;				
			}
			return null;
		}
		private final MonakServiceAnak monakService;
	}
}
